  <template>
  <div class="editProject">
    <a-modal 
      v-model:open="open"
      :title="title"
      @ok="handleOk"
      @cancel="handleCancel"
      width="40%"
    >
      <template #footer>
        <a-button key="back" @click="handleCancel">取消</a-button>
        <a-button key="submit" type="primary" @click="handleOk">确定</a-button>

    </template>

      <a-form 
        ref="formRef"
        :rules="rules"
        :model="formState"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        :hideRequiredMark="true"
      >
        <a-row>
          <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <a-form-item label="项目名称:" name="projectName">
              <a-input
                placeholder="请输入项目名称"
                v-model:value="formState.projectName"
                disabled="true"
              />
            </a-form-item>
          </a-col>

          <a-space
            v-for="(item, index) in formState.properties"
            :key="item.id"
            style="display: flex;"
            align="baseline"
        >
            <a-form-item
                :name="['properties', index, 'name']"
                :rules="{
                    required: true,
                    message: '字段名不能为空',
                }"
            >
                <a-input v-model:value="item.name" placeholder="请输入字段名" />
            </a-form-item>
            <a-form-item
                :name="['properties', index, 'value']"
                :rules="{
                    required: true,
                    message: '字段值不能为空',
                }"
            >
                <a-textarea v-if="item.name === 'publicKey'" v-model:value="item.value" placeholder="请输入字段值" />
                <a-input v-else v-model:value="item.value" placeholder="请输入字段值" />
                
            </a-form-item>
            <a-form-item
                :name="['properties', index, 'description']"
            >
                <a-input v-model:value="item.description" placeholder="请输入描述信息" />
            </a-form-item>
            <MinusCircleOutlined @click="removeProperty(item)" />
            </a-space>
          <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <a-button type="dashed" style="width: 100%" @click="addDomain">
                    <PlusOutlined />
                    添加项目属性
                </a-button>
          </a-col>
         
        </a-row>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive } from 'vue';
  import type { UnwrapRef } from 'vue';
  import { message } from 'ant-design-vue';
  import type { Rule } from 'ant-design-vue/es/form';
  import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons-vue';
  import { normalMixStringReg } from '@/utils/validate';
  import { MAddProjectFormState } from '@/utils/interface';
  import { SaveProject } from '@/api/index';
  
  const emit = defineEmits<{
    (event: 'loadProjectListsFun'): void
  }>();

  const labelCol = { style: { width: '70px' } };
  const wrapperCol = { span: 24 };
  const formRef = ref();
  const open = ref<boolean>(false);
  const title = ref<string>('编辑项目');
  const numberDisabled = ref<boolean>(false);

  const formState: UnwrapRef<MAddProjectFormState> = reactive({
    id: null,
    projectName: "",
    properties: []
  });

  const validateProjectName = (_rule: Rule, value: string) => {
    if (value === '' || value === null) {
      return Promise.reject('请输入项目名称');
    } else {
      if (!normalMixStringReg.test(value)) {
        return Promise.reject('请输入合法的项目名称');
      } else {
        return Promise.resolve();
      }
    }
  };
  const rules: Record<string, Rule[]> = {
    projectName: [{ validator: validateProjectName, trigger: 'blur' }],
    name: [{ required: true, message: '字段名不能为空', trigger: 'blur' }],
    value: [{ required: true, message: '字段值不能为空', trigger: 'blur' }]
  };

  const addDomain = () => {
    formState.properties.push({
        id: Date.now().toString(),
        projectId: formState.id,
        name: "",
        value: "",
        description: ""
    })
  }
  const removeProperty = (item: any) => {
    formState.properties = formState.properties.filter((i: any) => i.id !== item.id);
  }


  const showModal = (record: any) => {
    console.log('编辑项目', record);
    if(record) {
        formState.id = record.id;
        formState.projectName = record.projectName;
        if(record.properties === null || record.properties.length === 0) {
            formState.properties = [];
        } else {
            formState.properties = record.properties;
        }
    }
    open.value = true;
  }

  const handleOk = async () => {
    formRef.value
    .validate()
    .then(() => {
      AddAppFun();
    })
    .catch((error: any) => {
      console.log('error', error);
    });
  }

  const AddAppFun = async () => {
    if(formState.properties.length === 0) {
        message.error('请添加项目属性');
        return;
    }
    const properties = formState.properties.map((item: any) => {
        const baseItem = {
            projectId: formState.id,
            name: item.name,
            value: item.value,
        };
        return {
            ...baseItem,
            ...(typeof item.id === 'number' && { id: item.id }),
            ...(item.description?.trim() && { description: item.description }),
        };
    })
    const _params: MAddProjectFormState = {
        id: formState.id,
        projectName: formState.projectName,
        // properties: JSON.stringify(properties),
        properties: properties,
    };
    const res = await SaveProject(_params);
    if(res) {
      if(res.code === 1000) {
        message.success('编辑成功');
        emit("loadProjectListsFun");
        handleCancel();
      } else {
        message.error(res.msg);
      }
    }
  }

  const handleCancel = () => {
    formRef.value.resetFields();
    numberDisabled.value = false;
    formState.id =null;
    formState.projectName = "";
    formState.projectDesc = "";
    open.value = false;
  }
  defineExpose({ showModal });
</script>

<style lang="scss" scoped>
</style>